package TCP;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Cheng-02
 * @version V1.0
 * @Package test
 * @date 2024/4/3 10:39
 */
class Test08_TestPool {
    public static void main(String[] args) {
Pool pool = new Pool();
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 3; i++) {
            executorService.execute(pool);
        }
    }
}

class Pool implements Runnable {
    int ticket = 100;
    /**
     * run方法是线程的入口点，这里模拟了卖票的过程。
     * 通过synchronized关键字控制对票数的访问，以避免并发问题。
     */
    @Override
    public void run() {
        // 尝试让当前线程暂停1000毫秒，以模拟售票过程的延时
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (this) {
                // 当票数小于等于 0 时，结束卖票操作
                if (ticket <= 0) {
                    break;
                }
                // 输出卖票信息，并递减票数
                System.out.println(Thread.currentThread().getName() + "卖了" + ticket + "张票");
                ticket--;
            }
        }
    }
}
